<template>
  <div class="m-auto max-w-200">
    <div text-4xl>
      <div i-carbon-campsite inline-block/>
    </div>
    <div py-4/>
    <Form text="left"
          ref="formRef"
          :rules="formRules"
          :model="formState" :label-col="labelCol">
      <FormItem label="新客建档查询"
                :validate-status="phoneState.validateStatus"
                :help="phoneState.help"
      >
        <InputSearch
          :disabled="phoneState.disable"
          :loading="phoneState.loading"
          v-model:value="phoneState.value"
          placeholder="输入新客手机号查询是否建档"
          enter-button
          @search="handleInputSearch"
        />
      </FormItem>

      <TheObjectArrayTableShow v-if="phoneState.list.length" :list="phoneState.list"/>
      <template v-else-if=" phoneState.disable && !phoneState.list.length">
        <FormItem label="推荐人（顾客）查询"
                  :validate-status="selectFieldStatus"
                  :help="selectFieldHelp"
                  name="RecommendCustId"
        >
          <Select
            v-model:value="currentValue"
            show-search
            placeholder="查询推荐人"
            style="width: 100%"
            :filter-option="false"
            :not-found-content="selectSearchLoading ? undefined : null"
            :options="selectData"
            @search="handleSearch"
            @change="handleChange"
          >
            <template v-if="selectSearchLoading" #notFoundContent>
              <Spin size="small"/>
            </template>
          </Select>
        </FormItem>
        <FormItem label="客户姓名" name="CustName">
          <Input v-model:value="formState.CustName"
                 placeholder="请输入客户姓名"
          />
        </FormItem>
        <FormItem label="性别" name="Sex">
          <RadioGroup v-model:value="formState.Sex"
                      placeholder="请选择客户性别"

          >
            <Radio value="1">男</Radio>
            <Radio value="2">女</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="建档媒介" name="media">
          <Cascader v-model:value="formState.media"
                    disabled
                    :field-names="fieldNames"
                    :options="mediumStore.options"
                    @change="onMediumChange"
                    placeholder="请选择客户建档媒介"/>
        </FormItem>
        <FormItem label="建档类型" name="TmpCustRegType">
          <Select
            v-model:value="formState.TmpCustRegType"
            show-search
            placeholder="选择建档类型"
            :options="tempTypeStore.options"
            :filter-option="filterOption"
          ></Select>
        </FormItem>
        <FormItem label="建档人" name="CreatedBy">
          <Select
            v-model:value="formState.CreatedBy"
            show-search
            :disabled="disableCreatedBy"
            placeholder="选择员工建档人"
            :options="userStore.options"
            :filter-option="filterOption"
          ></Select>
        </FormItem>
        <FormItem label="推荐人（员工）" name="RecommendEmpId">
          <Select
            v-model:value="formState.RecommendEmpId"
            show-search
            placeholder="选择员工推荐人"
            :options="userStore.options"
            :filter-option="filterOption"
          ></Select>
        </FormItem>
        <FormItem label="建档备注">
          <Textarea :rows="4" v-model:value="formState.Remark"/>
        </FormItem>
      </template>
      <FormItem text-right v-if=" phoneState.disable">
        <Button v-if="!phoneState.list.length" type="primary" @click="onSubmit" :loading="loading">创建</Button>
        <Button style="margin-left: 10px" @click="handleClearForm">清空</Button>
      </FormItem>
    </Form>
  </div>
</template>
<script setup lang="ts">
import {
  CommonAreaCommonCustNamePhone,
  ReservationTempCustInfoIndex,
  ReservationTempCustInfoCreate
} from "~/requests";
import dayjs from 'dayjs'
import {useTempTypeStore} from "~/stores/tempType";
import {useUserStore} from "~/stores/user";
import {useMediumTypeStore} from "~/stores/mediumType";
import {
  Form,
  FormItem,
  Cascader,
  RadioGroup,
  Radio,
  Input,
  InputSearch,
  Select,
  Spin,
  Button,
  Textarea
} from "ant-design-vue"
import {sendMarkdownMessage} from "~/requests/dintTalkBot";
import {showModal} from "~/requests/method";

defineOptions({
  name: 'IndexPage',
})

useHead({
  title: '老带新建档工具',
});

interface FormState {
  media: [];
  RecommendCustId: string;
  RecommendEmpId: string;
  Phone: string;
  Sex: string;
  CustName: string;
  Remark: string;
  TmpCustRegType: string;
  CreatedBy: string;
  MediaSourceType: string;
  MediaSource: string;
}

const formRules: Record<string, Rule[]> = {
  RecommendCustId: [{required: true, message: '请输入推荐人（客户）', trigger: 'blur'}],
  RecommendEmpId: [{required: true, message: '请输入推荐人(员工)', trigger: 'blur'}],
  Phone: [{required: true, message: '请输入手机号', trigger: 'blur'}],
  Sex: [{required: true, message: '请选择性别', trigger: 'blur'}],
  CustName: [{required: true, message: '请输入客户姓名', trigger: 'blur'}],
  media: [{required: true, message: '请输入媒介', trigger: 'blur'}],
  TmpCustRegType: [{required: true, message: '请输入登记类型', trigger: 'blur'}],
  CreatedBy: [{required: true, message: '请输入登记人', trigger: 'blur'}],
}

const DEFAULT_CREATED_ID = "CCFB0947F9E04117B4B1B22800B6C411";

const formState: Ref<FormState> = reactive({
  media: ["E49078E79A214FF1A8C4AA0700E7A26D", "0CFF107755284EF4B6B34C5BD1FAC53D"],
  RecommendCustId: '',
  RecommendEmpId: DEFAULT_CREATED_ID,
  Phone: '',
  Sex: '2',
  CustName: '女士',
  Remark: '',
  MediaSourceType: "E49078E79A214FF1A8C4AA0700E7A26D",
  MediaSource: "0CFF107755284EF4B6B34C5BD1FAC53D",
  TmpCustRegType: "5FB93FF9FDD7495DAE9AAA4600E099DB",
  PlanRecallEmp: DEFAULT_CREATED_ID,
  CreatedBy: DEFAULT_CREATED_ID,
});
const loading = ref(false);

const notifyToDingTalkBot = () => {
  let recommendCustItem = selectData.value.find((item) => item.value === formState.RecommendCustId);
  if (!recommendCustItem) {
    return;
  }
  let userItem = userStore.options.find(item => item.value === formState.RecommendEmpId)
  if (!userItem) return;
  const msgArr = [
    `- 新客：${formState.Phone}`,
    `- 推荐顾客：${recommendCustItem.label}`,
    `- 推荐登记人：${userItem.label}`,
  ];
  sendMarkdownMessage(msgArr.join('\n\r'));
}

const onSubmit = () => {
  formRef.value
    .validate()
    .then(async () => {
      if (loading.value) return;
      const params = {
        RecommendCustId: formState.RecommendCustId,
        RecommendEmpId: formState.RecommendEmpId,
        Phone: formState.Phone,
        Sex: formState.Sex,
        Age: '20',
        CustName: formState.CustName,
        Remark: formState.Remark,
        MediaSourceType: formState.MediaSourceType,
        MediaSource: formState.MediaSource,
        TmpCustRegType: formState.TmpCustRegType,
        PlanRecallEmps: "",
        PlanRecallEmp: formState.CreatedBy,
        CreatedBy: formState.CreatedBy,
        IncomeCapacity: "IC_LIANGHAO",
        Country: "0",
        Province: "610000",
        City: "610100",
        Area: "",
        DatetimeReg: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      }
      try {
        loading.value = true;
        let response = await ReservationTempCustInfoCreate(params);
        if (response.data?.code === 0) {
          let data = JSON.parse(response.data.data);
          let msg = data.message;
          if (msg) {
            if (/(UQ_TEMP_CUST_INFO_ID_PHONE|电话已存在|唯一|触发Action: <\/\b>Create)/.test(msg))
              msg = '客户已存在，请勿重复创建';
          } else {
            msg = '客户已经创建成功';
            notifyToDingTalkBot();
          }
          showModal(msg);
        } else {
          let msg = response.data?.msg;
          if (msg && /(UQ_TEMP_CUST_INFO_ID_PHONE|电话已存在|唯一)|(触发Action:\ \ <\/b>Create)/.test(msg))
            msg = '客户已存在，请勿重复创建';
          else
            msg = msg || '创建错误';
          showModal(msg);
        }
        console.log("response", response);
      } catch (e) {
        console.error(e);
        showModal("创建错误");
      }
      cacheParams(params);
      loading.value = false;
    })
    .catch(error => {
      console.log('error', error);
    });
};
const CACHE_KEY = "_previous_params";
const cacheParams = (params) => {
  localStorage.setItem(CACHE_KEY, JSON.stringify(params));
}
const getCacheParams = () => {
  let data = JSON.parse(localStorage.getItem(CACHE_KEY) || "{}");
  if (!data) return;
  if (data?.['MediaSourceType'] && data?.['MediaSource']) {
    formState.MediaSourceType = data['MediaSourceType'];
    formState.MediaSource = data['MediaSource'];
    formState.media = [formState.MediaSourceType, formState.MediaSource];
  }
  if (data?.['RecommendEmpId'])
    formState.RecommendEmpId = data['RecommendEmpId'];

  if (data?.['TmpCustRegType'])
    formState.TmpCustRegType = data['TmpCustRegType'];
  if (data?.['PlanRecallEmp'])
    formState.CreatedBy = data['PlanRecallEmp'];
  if (data?.['CreatedBy'])
    formState.CreatedBy = data['CreatedBy'];

}
const labelCol = {style: {width: '150px'}};

let timeout: any;
let currentValue = '';

const formRef = ref();

const selectData = ref<any[]>([]);
const selectSearchValue = ref();
const selectFieldHelp = ref("输入推荐人手机号码后查询推荐人信息");
const selectFieldStatus = ref('');
const selectSearchLoading = ref(false);
const fieldNames = {label: 'name', value: 'key', children: 'children'}

function fetchValue(value: string, callback: any) {
  if (!value || !/^1[3-9]\d{9}$/.test(value)) {
    selectFieldStatus.value = 'error';
    selectFieldHelp.value = '请输入正确的电话号码';
    return;
  }
  if (timeout) {
    clearTimeout(timeout);
    timeout = null;
  }
  currentValue = value;

  function fake() {
    selectFieldStatus.value = 'validating';
    selectFieldHelp.value = '查询中...';
    selectSearchLoading.value = true;
    CommonAreaCommonCustNamePhone({
      term: value,
    })
      .then((response) => response.data)
      .then((response) => {
        selectSearchLoading.value = false;
        if (currentValue === value) {
          let json = JSON.parse(response.data);
          json = json?.map((item) => {
            return {
              value: item['id'],
              label: item['label'],
            }
          }) || [];
          if (!json.length) {
            selectFieldStatus.value = 'error';
            selectFieldHelp.value = '查询结果为空，客户不存在，请确认手机号码...';
          } else {
            selectFieldStatus.value = 'success';
            selectFieldHelp.value = '查询成功，请选择客户名.';
          }
          callback(json);
        }
      })
      .catch((error) => {
        console.error(error);
        selectSearchLoading.value = false;
      });
  }

  timeout = setTimeout(fake, 500);
}

const handleSearch = (val: string) => {
  fetchValue(val, (d) => selectData.value = d)
};
const handleChange = (val: any) => {
  selectSearchValue.value = val.value || val;
  formState.RecommendCustId = val.value || val;
};

const phoneState = reactive({
  value: "",
  help: "",
  validateStatus: '',
  loading: false,
  list: [],
  disable: false,
});

const handleInputSearch = async (searchValue: string) => {
  if (phoneState.loading || phoneState.disable) return;
  if (!searchValue || !/^1[3-9]\d{9}$/.test(searchValue)) {
    initPhoneState('error', "号码错误", false)
    return;
  }
  phoneState.list = [];
  initPhoneState('validating', "查询中", true)
  try {
    let response = await ReservationTempCustInfoIndex({
      Phone: searchValue,
      currentPage: '1',
    })
    let respData = response.data;
    if (respData.code !== 0) {
      initPhoneState("warning", respData.msg)
      return;
    }
    let data = response.data?.data.list;
    data = data?.map((item) => {
      return {
        "建档时间": item["建档时间"],
        "客户姓名": item["客户姓名"],
        "现场客服": item["现场客服"],
        "线上客服": item["线上客服"],
      }
    }) || [];
    phoneState.list = data;
    phoneState.disable = true;
    console.log("phoneState.list", phoneState.list);
    if (data.length) {
      initPhoneState("warning", "客户已经建档");
    } else {
      formState.Phone = searchValue;
      initPhoneState("success", "号码可以建档");
    }
  } catch (e) {
    initPhoneState('error', "查询失败")
  }
}

const initPhoneState = (validateStatus = '', help = '', loading = false) => {
  phoneState.validateStatus = validateStatus
  phoneState.help = help;
  phoneState.loading = loading;
}

const handleClearForm = () => {
  initPhoneState();
  phoneState.disable = false;
  phoneState.list = [];
  phoneState.value = '';
}

const tempTypeStore = useTempTypeStore();
const mediumStore = useMediumTypeStore();
const userStore = useUserStore();

const filterOption = (input: string, option: any) => {
  return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};

const onMediumChange = (val) => {
  formState.MediaSourceType = val[0] || '';
  formState.MediaSource = val[1] || '';
}

const disableCreatedBy = computed(() => {
  let userItem = userStore.options.find(item => item.value === DEFAULT_CREATED_ID)
  return !!userItem;
})

onMounted(() => {
  getCacheParams();
})

</script>
